﻿<template>
	<div class="diDeliverData-container">
		<el-card shadow="hover">
			<el-form :model="state.queryParams" ref="queryForm" :inline="true">
				<el-form-item :label-width='70' label="手机号">
					<el-input placeholder="请输入手机号" clearable class='ml10' @keyup.enter="handleQuery"
						v-model="state.queryParams.phone" />
				</el-form-item>
				<el-form-item :label-width='70' label="PID">
					<el-input placeholder="请输入PID" :clearable="true" class='ml10' @keyup.enter="handleQuery"
						v-model="state.queryParams.pid" />
				</el-form-item>
				<!-- <el-form-item :label-width='70' label="回传类型">
					<el-input placeholder="请输入信息流回传类型" clearable class='ml10' @keyup.enter="handleQuery"
						v-model="state.queryParams.deliverTypes" />
				</el-form-item> -->
				<el-form-item label="回传类型">
					<el-select v-model="state.queryParams.deliverType" placeholder="请输入信息流回传类型" :clearable="false"
						class="w100">
						<el-option v-for='item in optionDict.pageAccess' :key='item.value' :label='item.label'
							:value='item.value' />
					</el-select>
				</el-form-item>
				<el-form-item label="回传状态">
					<el-select v-model="state.queryParams.deliverStatus" placeholder="请输入信息流回传类型" :clearable="false"
						class="w100">
						<el-option v-for='item in optionDict.flowStatus' :key='item.value' :label='item.label'
							:value='item.value' />
					</el-select>
				</el-form-item>
				<!-- <el-form-item :label-width='70' label="日期">
					<el-date-picker v-model.trim="state.queryParams.selectDate" type="date" placeholder="选择日期"
						value-format="YYYY-MM-DD" style="width: 100%" :clearable="false" />
				</el-form-item> -->
				<el-form-item :label-width='70' label='日期'>
					<el-date-picker class='ml10' v-model='state.UTCDateRange' type='daterange'
						range-separator='至' start-placeholder='开始日期' end-placeholder='结束日期' :shortcuts='shortcuts'
						:disabled-date="disabledDate" @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'diDeliverData:query'">
							查询
						</el-button>
						<el-button icon="ele-Refresh" @click="resetQuery" v-auth="'diDeliverData:query'"> 重置
						</el-button>
					</el-button-group>
					<el-button icon="ele-FolderOpened" @click="exportExcel"> 导出 </el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<el-card shadow="hover" style="margin-top: 8px">
			<el-table :data="state.data" style="width: 100%" v-loading="state.loading" tooltip-effect="light"
				row-key="id" border stripe highlight-current-row>
				<el-table-column header-align="center" type="index" label="序号" width="55" align="center" />
				<el-table-column header-align="center" prop="createTime" label="创建时间" show-overflow-tooltip
					width="160" />
				<el-table-column header-align="center" prop="auId" label="访问用户Id" show-overflow-tooltip
					min-width="180" />
				<el-table-column header-align="center" prop="flowPName" label="平台" show-overflow-tooltip
					width="120" />
				<el-table-column header-align="center" prop="clickId" label="平台回传的ID" show-overflow-tooltip
					min-width="180" />
				<el-table-column header-align="center" prop="pid" label="Pid" show-overflow-tooltip min-width="190"
					align="center" />
				<el-table-column header-align="center" prop="deliverType" label="回传类型" show-overflow-tooltip
					width="130">
					<template #default="scope">
						<el-text v-for="item, index in optionDict.pageAccess"
							>{{ item.value == scope.row.deliverType ?
								item.label : '' }}</el-text>
					</template>
				</el-table-column>
				<el-table-column header-align="center" prop="phone" label="手机号码" show-overflow-tooltip width="115" />
				<el-table-column header-align="center" prop="deliverStatus" label="回传状态" align="center" show-overflow-tooltip
					width="100">
					<template #default="scope">
						<!-- <span v-for="item in optionDict.backfillingStatus">{{ item.value == scope.row.deliverStatus ?
							item.label : '' }}</span> -->

						<el-text v-for="item, index in optionDict.backfillingStatus"
							:type='item.value == 99 ? "danger" : "success"'>{{ item.value == scope.row.deliverStatus ?
								item.label : '' }}</el-text>
					</template>
				</el-table-column>
				<!-- <el-table-column header-align="center" prop="deliverTime" label="信息流回传时间传" show-overflow-tooltip width="130"/> -->
				<!-- <el-table-column header-align="center" prop="resData" label="回传应答数据" show-overflow-tooltip /> -->
				<el-table-column header-align="center" prop="requestIP" label="请求IP" show-overflow-tooltip
					width="130" />
				<el-table-column label="操作" width="100" align="center" fixed="right" show-overflow-tooltip>
					<template #default="scope">
						<el-button size="small" text type="primary" @click="openEditDiDeliverData(scope.row)"> 详情
						</el-button>
						<el-button size="small" text type="primary" @click="clickIdrule(scope.row.id)"> 调试
						</el-button>
					</template>

				</el-table-column>
			</el-table>
			<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
				:page-sizes="[20, 50, 100]" v-model:current-page="state.queryParams.pageNum" background
				v-model:page-size="state.queryParams.pageSize" layout="total, sizes, prev, pager, next, jumper"
				:total="state.total" />
			<EditDiDeliverData ref="editDiDeliverDataRef" :title="state.editTitle" />
		</el-card>
	</div>
</template>

<script lang="ts" setup name="diDeliverData">
import { onMounted, onUnmounted, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import mittBus from '/@/utils/mitt';
import EditDiDeliverData from '/@/views/delivery/operate/deliverData/component/editDiDeliverData.vue';
import { optionDict } from '/@/const/dict';
import { getFileName, downloadByData } from '/@/utils/download';
import { DiDeliverData } from '/@/api/models';
import SysDiDeliverDataApi from '/@/api/delivery/deliverData';
import { convertLocalDate, datePickerShortcuts } from '/@/utils/formatTime'

// 定义变量内容
const editDiDeliverDataRef = ref<InstanceType<typeof EditDiDeliverData>>();
// 定义变量内容
const shortcuts = datePickerShortcuts();
const state = reactive({
	loading: false,
	data: [] as Array<DiDeliverData>,
	UTCDateRange: [new Date(), new Date()],

	total: 0 as any,
	queryParams: {
		pageNum: 1,
		pageSize: 20,
		phone: '',
		deliverType: -1,
		pid: undefined,
		// selectDate: <Date><unknown>'',
			dateRange: [],
		deliverStatus:-1
	},
	editTitle: '',
});

onMounted(async () => {
	mittBus.on('submitRefresh', () => {
		handleQuery();
	});
});

onUnmounted(() => {
	mittBus.off('submitRefresh');
});

// 设置默认当前日期
const getDate = () => {
	var now = new Date();
	var year = now.getFullYear(); //得到年份
	var month = now.getMonth(); //得到月份
	var date = now.getDate(); //得到日期
	var hour = " 00:00:00"; //默认时分秒 如果传给后台的格式为年月日时分秒，就需要加这个，如若不需要，此行可忽略
	month = month + 1;
	month = month.toString().padStart(2, "0");
	date = date.toString().padStart(2, "0");
	state.queryParams.selectDate = `${year}-${month}-${date}`;//
}
getDate()

const formatLocalDate = async () => {
	if (state.UTCDateRange[0] as string)
		state.UTCDateRange[0] = new Date(state.UTCDateRange[0]);
	if (state.UTCDateRange[1] as string)
		state.UTCDateRange[1] = new Date(state.UTCDateRange[1]);

	if (state.UTCDateRange)
		state.queryParams.dateRange = [convertLocalDate(state.UTCDateRange[0]), convertLocalDate(state.UTCDateRange[1])];
	else
		state.queryParams.dateRange = [];
}

// 查询操作
const handleQuery = async () => {
	state.loading = true;
	await formatLocalDate();
	// state.queryParams.deliverType = -1;
	// if (state.queryParams.deliverTypes !== undefined) state.queryParams.deliverType = state.queryParams.deliverTypes;
	// delete state.queryParams.deliverTypes;
	const res = await SysDiDeliverDataApi().queryRecord(state.queryParams);
	state.data = res.data.result.items ?? [];
	state.total = res.data.result?.total;
	state.loading = false;
};

// 重置操作
const resetQuery = () => {
	state.queryParams.phone = '';
	state.queryParams.deliverType = -1;
	state.queryParams.pid = undefined;
	handleQuery();
};

// 打开新增页面
const openAddDiDeliverData = () => {
	state.editTitle = '添加';
	editDiDeliverDataRef.value?.openDialog({ status: 1 });
};

// 打开编辑页面
const openEditDiDeliverData = (row: DiDeliverData) => {
	state.editTitle = '详情';
	editDiDeliverDataRef.value?.openDialog(row);
};

// 删除
const delDiDeliverData = (row: any) => {
	ElMessageBox.confirm(`确定删除：【${row.name}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			let res = await SysDiDeliverDataApi().deletePost({ id: row.id });
			if (res.data.resCode != '0000')
				ElMessage.error(res.data.resMessage);
			else
				ElMessage.success("删除成功");
			await handleQuery();
		})
		.catch(() => { });
};

// 导出日志
const exportExcel = async () => {
	await formatLocalDate();
	SysDiDeliverDataApi().exportExcel(state.queryParams).then((res) => {
		state.loading = true;
		// console.log("excel.." + JSON.stringify(res));
		const fileName = getFileName(res.headers);
		downloadByData(res.data as any, fileName);
		var set = setTimeout(() => {
			state.loading = false;
			clearTimeout(set);
		}, 1500)
	});
};

// 改变页面容量
const onHandleSizeChange = (val: number) => {
	state.queryParams.pageSize = val;
	handleQuery();
};

// 改变页码序号
const onHandleCurrentChange = (val: number) => {
	state.queryParams.pageNum = val;
	handleQuery();
};

const clickIdrule = (id) => {
	ElMessageBox.confirm('是否调试?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		ElMessage.success({

			message: '调试成功!'
		});
		await SysDiDeliverDataApi().clickIdPost({ id: id });

	}).catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消调试'
		});
	});
}

// 日期不可选范围
const disabledDate = (time: Record<string, any>): boolean => {
    const today = new Date(); // 获取今天的日期
    today.setHours(0, 0, 0, 0); // 将时间设置为当天的零点
    return time.getTime() > today.getTime(); // 禁用今天之后的所有日期
}

</script>
